package com.notelapierdas.twitter;

import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.google.api.client.auth.oauth.OAuthAuthorizeTemporaryTokenUrl;
import com.google.api.client.auth.oauth.OAuthCredentialsResponse;
import com.google.api.client.auth.oauth.OAuthGetAccessToken;
import com.google.api.client.auth.oauth.OAuthGetTemporaryToken;
import com.google.api.client.auth.oauth.OAuthHmacSigner;
import com.google.api.client.http.apache.ApacheHttpTransport;

public class TokenAccesoOAuth extends Activity {

	private SharedPreferences sharedPreferences;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
	}

	@Override
	protected void onResume() {
		super.onResume();

		WebView webView = new WebView(this);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.setVisibility(View.VISIBLE);
		setContentView(webView);

		try {
			final OAuthHmacSigner signer = new OAuthHmacSigner();
			signer.clientSharedSecret = Constants.CONSUMER_SECRET;

			OAuthGetTemporaryToken tempToken = new OAuthGetTemporaryToken(
					Constants.REQUEST_URL);
			tempToken.transport = new ApacheHttpTransport();
			tempToken.signer = signer;
			tempToken.consumerKey = Constants.CONSUMER_KEY;
			tempToken.callback = Constants.OAUTH_CALLBACK_URL;

			OAuthCredentialsResponse tempCredentials = tempToken.execute();
			signer.tokenSharedSecret = tempCredentials.tokenSecret;

			OAuthAuthorizeTemporaryTokenUrl authorizeUrl = new OAuthAuthorizeTemporaryTokenUrl(
					Constants.AUTHORIZE_URL);
			authorizeUrl.temporaryToken = tempCredentials.token;
			String authorizationUrl = authorizeUrl.build();

			webView.setWebViewClient(new WebViewClient() {
				@Override
				public void onPageStarted(WebView view, String url,
						Bitmap bitmap) {
				//	Log.i("GoingSocial", "onPageStarted: " + url);
				}

				@Override
				public void onPageFinished(WebView view, String url) {
					// solo si estamos interceptando la URL de callback
					if (url.contains(Constants.OAUTH_CALLBACK_URL)) {
						try {
							if (url.indexOf("oauth_token=") != -1) {
								String requestToken = extractParamFromUrl(url,
										"oauth_token");
								String verificador = extractParamFromUrl(url,
										"oauth_verifier");

								signer.clientSharedSecret = Constants.CONSUMER_SECRET;

								OAuthGetAccessToken accessToken = new OAuthGetAccessToken(
										Constants.ACCESS_URL);
								accessToken.transport = new ApacheHttpTransport();
								accessToken.temporaryToken = requestToken;
								accessToken.signer = signer;
								accessToken.consumerKey = Constants.CONSUMER_KEY;
								accessToken.verifier = verificador;

								OAuthCredentialsResponse credentials = accessToken
										.execute();
								signer.tokenSharedSecret = credentials.tokenSecret;

								String[] credenciales = { credentials.token,
										credentials.tokenSecret };
								new AlmacenCredenciales(sharedPreferences)
										.escribe(credenciales);
								view.setVisibility(View.INVISIBLE);
								TokenAccesoOAuth.this.finish();

							} else if (url.indexOf("error=") != -1) {
								view.setVisibility(View.INVISIBLE);
								new AlmacenCredenciales(sharedPreferences).borra();
								   TokenAccesoOAuth.this.finish();

							}
						} catch (Exception ex) {
//							Log.e("GoingSocial",
//									"Excepcion en onPageFinished: "
//											+ ex.getMessage());
						}
					}
//					Log.i("GoingSocial", "onPageFinished: " + url);

				}

				private String extractParamFromUrl(String url, String paramName) {
					String queryString = url.substring(url.indexOf("?", 0) + 1,
							url.length());
					QueryStringParser queryStringParser = new QueryStringParser(
							queryString);
					return queryStringParser.getQueryParamValue(paramName);
				}
			});
			webView.loadUrl(authorizationUrl);
		} catch (Exception ex) {
//			Log.e("GoingSocialTwitter", "Error: " + ex);
		}

	}
	

}
